package com.appspot.yourvirtualgymtrainer;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.logging.Level;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.Entity;


public class UserServlet extends BaseServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			 throws ServletException, IOException {

		}
	
	/**
	 * Creates entity and persists the same
	 */
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		HttpSession sess = req.getSession(true);
		// sprawdzenie czy put pochodzi od logowania
		String isLogin = req.getParameter("isLogin");
		isLogin = isLogin.trim().toLowerCase();
		String isRegister = req.getParameter("isRegister");
		isRegister = isRegister.trim().toLowerCase();
		System.out.println("islogin"+isLogin+" is register " + isRegister);
		if(isLogin.compareTo("yes") == 0 && isRegister.compareTo("no") == 0) {
			String login = req.getParameter("login");
			login = login.trim().toLowerCase();
			String password = req.getParameter("password");
			password = password.trim().toLowerCase();
			Entity user = UserSOP.getUser(login);
			Map<String, Object> userProperities= user.getProperties();
			
			String loginPassword = (String) userProperities.get("password");
			System.out.println("loguje na  " + userProperities.get("login") + " " + loginPassword);
			if(user != null && loginPassword.compareTo(password) == 0) {
				sess.setAttribute("isLogged", login);
				resp.setContentType("text/plain; charset=utf-8");
				out.println("zalogowany");
			} else {
				  sess.setAttribute("isLogged", "no");
			}
		} else if(isLogin.compareTo("no") == 0 && isRegister.compareTo("yes") == 0) {
			String loginRegister = req.getParameter("loginRegister");
			String passwordRegister = req.getParameter("passwordRegister");
			String email = req.getParameter("email");
			//sprawdzamy unnikalnosc nickow
			Entity isUser = UserSOP.getUser(loginRegister);
	        if(isUser == null) {
	        	UserSOP.updateUser(loginRegister, passwordRegister, email);
	        	resp.setContentType("text/plain; charset=utf-8");
				out.println("zarejestrowany");
	        } else {
	        	resp.setContentType("text/plain; charset=utf-8");
	        	out.println("zajety");
	        }

		} 
	}
}
